package inc.sneid.reminderSpring.controllers;

import inc.sneid.reminderSpring.domains.Deltas;
import inc.sneid.reminderSpring.exceptions.DeltasLongIncorrect;
import inc.sneid.reminderSpring.services.DeltasService;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("deltas")
public class DeltasController {

    public static final long DAY = 24*60*60*1000;

    private final DeltasService deltasService;

    public DeltasController(DeltasService deltasService) {
        this.deltasService = deltasService;
    }

    @GetMapping("{name}")
    public Deltas get(@PathVariable Deltas name){
        return name;
    }

    @GetMapping("all")
    public Page<Deltas> all(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer size){
        Pageable pageable = PageRequest.of(page, size);
        return deltasService.getPage(pageable);
    }

    @PostMapping("new")
    public Deltas newDeltas(@RequestBody @Valid Deltas deltas) throws DeltasLongIncorrect {
        for (var delta : deltas.getDeltas()) {
            if (delta < DAY){
                throw new DeltasLongIncorrect("Value of each element of list deltas must be greater than DAY(86400000)");
            }
        }
        return deltasService.save(deltas);
    }

    @DeleteMapping
    public void delete(@RequestParam String name){
        deltasService.deleteByName(name);
    }

}
